package com.atguigu.demo02.test02;

import sun.applet.Main;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author gjl
 * @create 2021-04-25 13:58
 *
 * 数组线程不安全问题
 *
 * 出现错误
 * ConcurrentModificationException 并发修改异常
 *
 * 解决方案
 * 1. new Vector();
 * 2. Collections.synchronizedList(new ArrayList<>())
 * 3. new CopyOnWriteArrayList<>()  写时复制技术
 *
 * 优化建议
 * 读多写少时候，有用CopyOnWriteArrayList类解决线程安全问题
 */
public class Test {
    /*public static void main(String[] args) {
        //List<String> list = new Vector();//new ArrayList();//java.util.ConcurrentModificationException 并发修改异常  线程不安全
        //List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }*/

    /*public static void main(String[] args) {
        Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet(new HashSet<>());//new HashSet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }*/

    public static void main(String[] args) {
        //Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet(new HashSet<>());//new HashSet<>();
        //Map<String,String> map = Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

}
